package com.Oz.Interceptor;

import com.Oz.Annotation.CurrentLimit;
import com.Oz.Util.redisUtil;
import org.springframework.data.redis.RedisConnectionFailureException;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author Khan Liu
 * @date 2022/7/14 10:52
 */

public class LimitInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler){

        if (handler instanceof HandlerMethod) {
            HandlerMethod method = (HandlerMethod) handler;
            CurrentLimit limit = method.getMethodAnnotation(CurrentLimit.class);
            if (limit != null) {
                int second = limit.second();
                int maxCount = limit.maxCount();
                String key = request.getHeader("X-Real-IP") + method.getMethod().getName();
                System.out.println(key);
                try {
                    Long cnt = redisUtil.redis.opsForValue().increment(key, second);
//                    long cnt = redisService.incr(key, second);
                    System.out.println(redisUtil.redis.opsForValue().get(key));
                    if (cnt > maxCount) {
                        return false;
                    }
                    return true;
                } catch (RedisConnectionFailureException e) {
                    e.printStackTrace();
                    return true;
                }
            }
        }
        return false;
    }
}
